<template>
  <div class="app-container">
    
        <el-select id="cj_select" v-model="selectedScene" placeholder="请选择战场场景">
          <el-option
            v-for="item in scenetable"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            @click.native="getSslListBySceneID(item.value)"
          />
        </el-select>
        <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        height="35vh"
        
        @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="杀伤链"
            sortable
            width="100">
            <template slot-scope="scope">{{ "杀伤链-"+scope.row.id }}</template>
          </el-table-column>
          <el-table-column
            prop="spyEquipment"
            label="侦察探测装备"
            width="200">
          </el-table-column>
          <el-table-column
            prop="identificationEquipment"
            label="指挥控制装备"
            width="200">
          </el-table-column>
    <!--      <el-table-column-->
    <!--        prop="decisionEquipment"-->
    <!--        label="火力打击装备"-->
    <!--        width="200">-->
    <!--      </el-table-column>-->
          <el-table-column
            prop="strikeEquipment"
            label="火力打击装备"
            width="200">
          </el-table-column>
          <el-table-column
            prop="time"
            label="时间"
            sortable
            width="120">
          </el-table-column>
          <el-table-column
            prop="precision"
            label="准确度(%)"
            sortable
            width="120">
          </el-table-column>
          <el-table-column
            prop="accuracy"
            label="精度(%)"
            sortable
          >
          </el-table-column>
          <el-table-column
            prop="w"
            label="综合评估"
            sortable
            show-overflow-tooltip>
          </el-table-column>
        </el-table>
        <div style="margin-top: 20px">
          <el-button @click="toggleSelection([tableData[1], tableData[2]])">对比</el-button>
          <!-- <el-button @click="toggleSelection()">取消选择</el-button> -->
          <span style="height: 50px; margin-left:50px;">
            <el-tag>综合评估指标W=w1*[-(时间/tMax)^k]+w2*精度+w3*准确度</el-tag>
            <el-tooltip content="时间链系数" placement="top" class="tip">
              <el-tag type="success">w1:</el-tag>
            </el-tooltip>
            
            <el-input v-model="w1" class="value-input" size="small" placeholder="时间链系数"></el-input>
            <el-tooltip content="最大执行时间" placement="top" class="tip">
              <el-tag type="success">tMax:</el-tag>
            </el-tooltip>
            <el-input v-model="tMax" class="value-input" size="small" placeholder="最大执行时间"></el-input>
            <el-tooltip content="指数" placement="top" class="tip">
              <el-tag type="success">k:</el-tag>
            </el-tooltip>
            <el-input v-model="k" class="value-input" size="small" aria-placeholder="指数"></el-input>
            <el-tooltip content="准确度链系数" placement="top" class="tip">
              <el-tag type="success">w2:</el-tag>
            </el-tooltip>
            <el-input v-model="w2" class="value-input" size="small" placeholder="准确度链系数"></el-input>
            <el-tooltip content="精度链系数" placement="top" class="tip">
              <el-tag type="success">w3:</el-tag>
            </el-tooltip>    
            <el-input v-model="w3" class="value-input" size="small" placeholder="精度链系数"></el-input>
          </span>
        </div>
     
        <!-- Flex布局的容器 -->
        <div class="flex-container1">
          <!-- 三个等宽的div -->
          <!-- <div class="flex-item" id="timeChain">Div 1</div> -->
          <div class="flex-item" id="wChain">综合评估</div>
          <!-- <div class="flex-item" id="accuracyChain">Div 3</div> -->
        </div>
     


  </div>
  </template>

  <script>
  import * as echarts from 'echarts';
  import { getList, getChainInfo, getSslListBySceneID, getSceneList } from '@/api/ssl'
  export default {
    data() {
      return {
        w: 0,
        w1: 1,
        w2: 0,
        w3:0,
        tMax:250,
        k:4,
        selectedScene:null,
        scenetable:[],
        echartsInstances: [], // 用于存储 ECharts 实例
        tableData: [],
        multipleSelection: [],
        timeChainOption: {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                // Use axis to trigger tooltip
                type: 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
              }
            },
            legend: {},
            grid: {
              left: '5%',
              right: '5%',
              bottom: '3%',
              containLabel: true
            },
            yAxis: {
              type: 'value',
              position: 'right',
              name: '时间/s'
            },
            xAxis: {
              type: 'category',
              // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
              data:[]
            },
            series: [
              {
                name: 'F1发现',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                data: [320, 302, 301, 334, 390, 330, 320]
              },
              {
                name: 'F2定位',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                data: [10, 1320, 101, 134, 90, 230, 210]
              },
              {
                name: 'T1跟踪',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                data: [220, 182, 191, 234, 290, 330, 310]
              },
              {
                name: 'T2瞄准',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                data: [150, 212, 201, 154, 190, 330, 410]
              },
              {
                name: 'E打击',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                data: [820, 832, 901, 934, 1290, 1330, 1320]
              },
              {
                name: 'A评估',
                type: 'bar',
                stack: 'total',
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                data: [820, 832, 901, 934, 1290, 1330, 1320]
              }
            ]
          },
        precisionChainOption:{
          tooltip: {
              trigger: 'axis',
          },
            xAxis: {
              type: 'category',
              // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
              data:[]
            },
            yAxis: {
              name:'准确度/%',
              position:'right',
              type: 'value',
            },
            grid: {
              left: '5%',
              right: '5%',
              bottom: '3%',
              containLabel: true
            },
            series: [
              {
                data: [
                  120,
                  {
                    value: 200,
                    itemStyle: {
                      color: '#a90000'
                    }
                  },
                  150,
                  80,
                  70,
                  110,
                  130
                ],
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                type: 'bar'
              }
            ]
          },
        wChainOption:{
          tooltip: {
              trigger: 'axis',
          },
          xAxis: {
            type: 'category',
            // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
            data:[]
          },
          yAxis: {
            name:'综合评估',
            position:'right',
            type: 'value',
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '3%',
            containLabel: true
          },
          series: [
            {
              data: [
                120,
                {
                  value: 200,
                  itemStyle: {
                    color: '#a90000'
                  }
                },
                150,
                80,
                70,
                110,
                130
              ],
              label: {
                show: true
              },
              emphasis: {
                focus: 'series'
              },
              type: 'bar'
            }
          ]
        },
        accuracyChainOption:{
          tooltip: {
              trigger: 'axis',
          },
            xAxis: {
              type: 'category',
              // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
              data:[]
            },
            yAxis: {
              name:'精度/%',
              position:'right',
              type: 'value'
            },
            grid: {
              left: '5%',
              right: '5%',
              bottom: '3%',
              containLabel: true
            },
            series: [
              {
                data: [
                  120,
                  200,
                  {
                    value: 200,
                    itemStyle: {
                      color: '#a90000'
                    }
                  },
                  150,
                  80,
                  70,
                  110,
                  130
                ],
                label: {
                  show: true
                },
                emphasis: {
                  focus: 'series'
                },
                type: 'bar'
              }
            ]
        }
      }
    },

    methods: {
      check021(value){
        value=Number(value)
        console.log(typeof(value))
        if(typeof(value)=="number"&&value>=0&&value<=1){
          return true
        }else{
          return false
        }
      },
      getssl(){
        if(this.selectedScene==null){
        return 
      }
      const scene_id = parseInt(this.selectedScene.match(/\d+/)[0])
      console.log("sceneId")
      console.log(scene_id)
        getList(scene_id)
        .then(response => {
          console.log("getssl/getlist")
          console.log(response)
          // Assuming the response contains an array of SSL data
          this.tableData = response.data.map(item => {
              // 使用replace方法去掉字符串两侧的方括号
              const modifiedItem = {
                  ...item,
                  spyEquipment: item.spyEquipment.replace(/^\[|\]$/g, ''),
                  identificationEquipment: item.identificationEquipment.replace(/^\[|\]$/g, ''),
                  // decisionEquipment: item.decisionEquipment.replace(/^\[|\]$/g, ''),
                  strikeEquipment: item.strikeEquipment.replace(/^\[|\]$/g, '')
              };
              
              return modifiedItem;
          });
          this.tableData.forEach(item => {
            item.time = item.time.toFixed(2);
            item.accuracy=(item.accuracy*100.0).toFixed(2);
            item.precision=(item.precision*100.0).toFixed(2);
            item.interceptionP=(item.interceptionP*100.0).toFixed(2);
            item.p0=(item.p0*100.0).toFixed(2);
            item.p1=(item.p1*100.0).toFixed(2);
            item.p2=(item.p2*100.0).toFixed(2);
            item.w='-'
          });
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
      },
      getChainInfoHelp(idList){
        getChainInfo(idList)
          //axios.post('http://localhost:8081/ssl/chainInfo',idList)
          .then(response => {
            // 处理后端的响应
            console.log(response);
            this.timeChainOption.xAxis.data=this.multipleSelection.map(item => "杀伤链-"+item.id)
            this.precisionChainOption.xAxis.data=this.multipleSelection.map(item => "杀伤链-"+item.id)
            this.accuracyChainOption.xAxis.data=this.multipleSelection.map(item => "杀伤链-"+item.id)
            this.timeChainOption.series[0].data=response.data.t0
            this.timeChainOption.series[1].data=response.data.t1
            this.timeChainOption.series[2].data=response.data.t2
            this.timeChainOption.series[3].data=response.data.t3
            this.timeChainOption.series[4].data=response.data.t4
            this.timeChainOption.series[5].data=response.data.t5
            this.precisionChainOption.series[0].data=response.data.p.map(item=>(item*100).toFixed(2))
            this.accuracyChainOption.series[0].data=response.data.v.map(item=>(item*100).toFixed(2))
            // this.drawLine()
          })
          .catch(error => {
            // 处理请求错误
            console.error(error);
          });
      },
      getChainInfo(){
        const idList=this.multipleSelection.map(item => item.id)
        
        //console.log(idList);
        this.getChainInfoHelp(idList);
      },
      toggleSelection() {
        this.tableData.forEach(item=>{
          item.w='-';
        })
        if(!this.check021(this.w1)||!this.check021(this.w2)||!this.check021(this.w3)){
          this.$message({
            message: '输入的值必须在0到1之间',
            type: 'error'
          });
          return
        }
        // this.tableData.forEach(item => {
        //   // 更新 age 列
        //   item.w += 1;
        //   // 更新 gender 列
        //   // item.gender = (item.gender === 'Male') ? 'Female' : 'Male';
        // });
        this.w1=Number(this.w1)
        this.w2=Number(this.w2)
        this.w3=Number(this.w3)
        if(this.w1+this.w2+this.w3!=1){
          this.$message({
            message: 'w1,w2,w3之和必须为1',
            type: 'error'
          });
          return
        }
        this.getChainInfo()
        // this.drawLine()
        const list=this.multipleSelection.map(item => item)
        console.log("选中了")
        console.log(list)
        
        
        let max=0
        let bestId=[]
        let count=0
        this.wChainOption.series[0].data=[];
        this.wChainOption.xAxis.data=[];
        for(let i=0;i<list.length;i++){
          if(i==0)
            max=this.w1*[-Math.pow(((list[i].time*1.0)/(1.0*this.tMax)),this.k)+1]+this.w2*list[i].precision*0.01+this.w3*list[i].accuracy*0.01
          if(parseFloat(list[i].time)>parseFloat(this.tMax)){
            count=count+1
          }
        }
        console.log('count:'+count);
        if(count==list.length){
          this.$message({
            message: '没有最优杀伤链',
            type: 'error'
          });
          return
        }
        console.log("max=",max);
        list.forEach(ssl=>{
          console.log("ssl.time=",ssl.time);
          console.log("tMax=",this.tMax);
          console.log("ssl.time/tMax=",ssl.time*1.0/this.tMax);
          // console.log("ssl.time/tMax^k+1=",(-((ssl.time*1.0)/(1.0*this.tMax))^(0.1*this.k)+1));
          let w=this.w1*[-Math.pow(((ssl.time*1.0)/(1.0*this.tMax)),this.k)+1]+this.w2*ssl.precision*0.01+this.w3*ssl.accuracy*0.01
          console.log("w=",w);
          if(w>0){
            this.wChainOption.series[0].data.push(w.toFixed(4));
            this.wChainOption.xAxis.data.push("杀伤链-"+ssl.id);
          }
          
          if(w>max){
            console.log("wmax=",w);
            max=w
            bestId=[ssl.id]
          }
          else if(w==max){
            bestId.push(ssl.id)
          }
        })
        max=max.toFixed(4)
        console.log('max',max);
        

        
        // this.$message({
        //     message: '杀伤链-'+bestId+"是最优杀伤链",
        //     type: 'success'
        //   });
        // this.wChainOption.xAxis.data=this.multipleSelection.map(item => "杀伤链-"+item.id)
        // bestId.forEach(best=>{
            
        // })
        
        console.log('this.wChainOption.series[0].data',this.wChainOption.series[0].data);
        console.log('this.wChainOption.xAxis.data',this.wChainOption.xAxis.data);
        console.log('this.tableData',this.tableData);
        // 使用 JSON 方法进行深拷贝
        const deepCopyTableData = JSON.parse(JSON.stringify(this.wChainOption.series[0].data));

        // 假设 this.wChainOption.xAxis.data 和 this.wChainOption.series[0].data 都是正确的数组

        // 遍历 this.wChainOption.xAxis.data
        this.wChainOption.xAxis.data.forEach((label, index) => {
            // 从 label 中提取数字
            const labelNumber = parseInt(label.match(/\d+/)[0]);

            // 通过提取的数字与 id 匹配对应的记录
            const tableDataIndex = this.tableData.findIndex(entry => entry.id === labelNumber);

            // 如果找到了对应的记录
            if (tableDataIndex !== -1) {
              const updatedItem = Object.assign({}, this.tableData[tableDataIndex], {
                w: parseFloat(deepCopyTableData[index])
              });

              const clonedData = JSON.parse(JSON.stringify(this.tableData));
              clonedData[tableDataIndex] = updatedItem;

              this.tableData = clonedData;
            }
            this.wChainOption.series[0].data = this.wChainOption.series[0].data.map(item => {
            if (item === max) {
              return {
                value: item,
                itemStyle: {
                  color: '#AAD9BB'
                }
              };
            }
            return item;
          });

          console.log(this.wChainOption.series[0].data);
            // 使用 $forceUpdate
            // this.$forceUpdate();
        });
        // 遍历 this.wChainOption.xAxis.data
        // this.tableData = this.wChainOption.xAxis.data.map((label, index) => {
        //     const labelNumber = parseInt(label.match(/\d+/)[0]);
        //     const tableDataIndex = this.tableData.findIndex(entry => entry.id === labelNumber);

        //     if (tableDataIndex !== -1) {
        //         return Object.assign({}, this.tableData[tableDataIndex], { w: parseFloat(this.wChainOption.series[0].data[index]) });
        //     } else {
        //         return this.tableData[tableDataIndex];
        //     }
        // });
        console.log('this.tableData',this.tableData);
        // 现在，tabledata 中的 w 字段已经根据对应关系更新

        // this.accuracyChainOption.series[0].data=response.data.v.map(item=>(item*100).toFixed(2))
        this.drawLinew()
        
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      drawLinew() {
          // 初始化echarts实例
          let wChain = echarts.init(document.getElementById('wChain'))
          
          this.echartsInstances = [wChain];
          // 绘制图表
          // timeChain.setOption(this.timeChainOption);
          // precisionChain.setOption(this.precisionChainOption)
          // accuracyChain.setOption(this.accuracyChainOption)
          wChain.setOption(this.wChainOption)
          this.reloadPage()
        },
      drawLine() {
          // 初始化echarts实例
          let timeChain = echarts.init(document.getElementById('timeChain'))
          let precisionChain = echarts.init(document.getElementById('precisionChain'))
          let accuracyChain = echarts.init(document.getElementById('accuracyChain'))
          this.echartsInstances = [timeChain, precisionChain, accuracyChain];
          // 绘制图表
          timeChain.setOption(this.timeChainOption);
          precisionChain.setOption(this.precisionChainOption)
          accuracyChain.setOption(this.accuracyChainOption)
          this.reloadPage()
        },
      reloadPage() {
        // 页面刷新
        this.echartsInstances.forEach(instance => {
          instance.resize();
        });
      },
      handleRouter(){
        this.getSslListBySceneID(this.selectedScene)
      },
      getScene(){
        getSceneList()
          .then(response=>{
            this.scenetable=response.data.map(item=>{
              return{
                value:'选项'+item.sceneId,//设置value的值
                // label:'战场场景'+item.sceneId//设置label的值
                label:item.name,
              }
            })
          })
      },
      getSslListBySceneID(selectedValue){
        
        console.log("getSslListBySceneID");
        if(selectedValue==null)
          return
        console.log(selectedValue);
        
        this.selectedScene=selectedValue
        this.getssl()
        
        const ssl_id = parseInt(selectedValue.match(/\d+/)[0])
      },
    },
    mounted() {
      this.getScene()
      console.log("sceneId"+this.$route.query.selectedScene);
      this.selectedScene = this.$route.query.selectedScene;
      this.handleRouter();
      // this.handleRouter()
      this.getssl();
      this.getChainInfo();
      // await this.drawLine();
      // this.check();
      window.addEventListener('resize', this.reloadPage);
    },
    beforeDestroy() {
    window.removeEventListener('resize', this.reloadPage);
    },
  }
  </script>

<style scoped>
  .line{
    text-align: center;
  }
  .flex-container {
    margin-top: 20px; /* 设置顶部边距以区分三个div */
    display: flex;
    height: 60vh; /* 设置高度为视口高度的50% */
  }
  .flex-container1 {
    /*margin-top: 20px; /* 设置顶部边距以区分三个div */
    display: flex;
    height: 50vh; /* 设置高度为视口高度的50% */
  }
  .flex-item {
    display: flex;
    flex: 1;
    border: 1px solid #ccc; /* 添加边框以示区分 */
    padding: 10px; /* 添加内边距以美化样式 */
    height: 80%;
    /* width: 90%; */
  }
  .app-container{
    width:100%
  }

  .value-input{
    width: 60px;
   /* margin-left:10px; */
   margin-right:10px;
  }
  .el-tag{
    margin: 0 5px;
    font-size: 14px;
  }
  .tip{
    width: unset;
  }
</style>

